<?php
/**
 * User: Titan
 * Date: Oct 22, 2010
 * Time: 7:21:05 PM
 */

$main = 'milestone';

/**
 * milestone()
 * 
 * this function is called immediately after all variables have been loaded and all forms
 * have been validated and submitted
 * 
 * @param mixed $vars
 * @return
 */
function milestone(&$vars)
{
	system_add_styles('assets/css/style.css');
	system_add_js('assets/js/jquery.js');
	
	$breadcrumbs = array(
		'Home' => array(
			'#title' => 'Home',
			'#anchor' => 'Home',
			'#attributes' => array(
				'class' => 'breadcrumb'
			),
			'#href' => base_path()
		)
	);
	
	if (!isset($GLOBALS['op']))
	{
		system_add_js('assets/js/selectable.table.js');
		system_page_title('Milestones');
	} 
	else
	{
		$breadcrumbs['Milestones'] = array(
			'#title' => 'Milestones',
			'#anchor' => 'Milestones',
			'#attributes' => array(
				'class' => 'breadcrumb'
			),
			'#href' => base_path() . 'milestone'
		);
	}
	
	system_breadcrumbs($breadcrumbs);
}

/**
 * milestone_prerender_page()
 * 
 * this function sets the content variable for the page.tpl.php template and any other data
 * such as page titles, etc.
 * 
 * This function also chooses which forms to display based on query string parameters
 * (ie. ?op=edit or ?op=add, etc.)
 * 
 * @param mixed $vars
 * @return
 */
function milestone_prerender_page(&$vars)
{
	global $milestone_form, $milestone_table, $op, $subop;
	
	$output = '';
	switch ($op)
	{
		case 'add':
		case 'edit':
		case 'clone':
		case 'delete':
			if (isset($vars['query']['mid']))
			{
				if (!isset($milestone_form))
				{
					if ($op != 'delete')
					{
						milestone_edit_form($vars['query']['mid']);
					}
					else 
					{
						milestone_delete_confirmation_form($vars['query']['mid']);
					}
				}
				
				$output = form_build($milestone_form, 'milestone_view_' . $op);
				system_page_title(ucwords($op) . ' Milestone');
			}
			else 
			{
				system_redirect(base_path() . 'milestone');
			}
			
			break;
		default: 
			if (!isset($milestone_form))
			{
				$milestone_form = milestone_default_form();
			}
			
			if (!isset($milestone_table))
			{
				$milestone_table = milestone_default_table();
			}
			
			system_page_title('Milestones');
				
			$add_button = array(
				'#type' => 'button',
				'#value' => 'add',
				'#id' => render_unique_id('add-milestone'),
				'#attributes' => array(
					'class' => 'ui-button add form-submit',
					'onclick' => "window.location = '" . base_path() . "milestone?op=add&mid=0';"
				),
				'#title' => '+ Add Milestone',
				'#prefix' => '<div class="form-item form-submit">',
				'#suffix' => '</div>'
			);
				
			if (isset($subop) && $subop == 'search')
			{
				system_page_title('Search Milestones');
				$reset_button = array(
					'#type' => 'button',
					'#value' => 'clear',
					'#id' => render_unique_id('clear-search'),
					'#attributes' => array(
						'class' => 'ui-button clear form-submit',
						'onclick' => "window.location = '" . base_path() . "milestone';"
					),
					'#title' => 'Clear Search',
					'#prefix' => '<div class="form-item form-submit">',
					'#suffix' => '</div>'
				);
			}
			else
			{
				system_page_title('Milestones');
			}
			
			$form_output = render('generic_button', $add_button) . (isset($reset_button) ? render('generic_button', $reset_button) : '') . form_build($milestone_form, 'milestone_view' . (empty($op) ? '' : '_' . $op));
			
			$output .= $form_output . render('table', $milestone_table);
			
			break;
	}
	
	$vars['content'] = $output;
}

/**
 * milestone_default_table()
 * 
 * This function returns the default table for the page (ie. the table that is rendered) with no 
 * query string parameters
 * 
 * In this case, this returns a table that lists all milestones
 * 
 * @return
 */
function milestone_default_table()
{
	$result = db_query('SELECT * FROM milestone WHERE mid > 0 ORDER BY name');
	
	$headers = array('', 'Name', 'Date');

	$edit_link =  array(
		'#anchor' => 'Edit',
		'#attributes' => array(
			'class' => 'action-link edit'
		),
		'#title' => 'Edit'
	);
	
	$rows = array();
	while ($milestone = db_fetch_array($result))
	{
		$link = $edit_link;
		$link['#href'] = base_path() . 'milestone?op=edit&mid=' . $milestone['mid'];
		$rows[] = array(
			'#cells' => array(
				'edit' => a($link),
				'name' => $milestone['name'],
				'date' => Milestone::formatted_date($milestone['date'])
			)
		);
	}
	
	if (empty($rows))
	{
		$rows[] = array(
			'#cells' => array(
				'no_results' => array(
					'#value' => '<h2 style="text-align:center;">Your search returned no results.</h2>',
					'#attributes' => array(
						'colspan' => count($headers)
					)
				)
			)
		);
	}
	
	$table_id = render_unique_id('milestone-table');
	$milestone_table = array(
		'#attributes' => array(
			'id' => $table_id,
			'border' => 1,
			'cellspacing' => 0,
			'cellpadding' => 8,
			'class' => 'selectable data-list-table'
		),
		'#header' => $headers,
		'#rows' => $rows
	);
	
	return $milestone_table;
}

/**
 * milestone_default_form()
 * 
 * This function returns the default form for the page (ie. the table that is rendered) with no 
 * query string parameters
 * 
 * @return
 */
function milestone_default_form()
{
	$form_id = render_unique_id('milestone-default-view');
	$form = array(
		'#id' => $form_id,
		'#action' => base_path() . 'milestone?op=view&subop=search',
		'#method' => 'POST',
		'#callback' => 'milestone_search_submit',
		'#attributes' => array(
			'class' => 'container-inline search-form'
		),
		'#inputs' => array(
			'name' => array(
				'#type' => 'textfield',
				'#id' => render_unique_id('filter-name'),
				'#title' => 'Name',
				'#size' => 45
			),
			'search_wrapper' => array(
				'#type' => 'html',
				'#value' => '<div class="form-item-wrapper search">'
			),
			'search' => array(
				'#type' => 'submit',
				'#value' => 'Search',
				'#id' => render_unique_id('search'),
				'#attributes' => array(
					'class' => 'ui-button search',
					'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "milestone?op=view&subop=search');"
				)
			),
			'search_wrapper_close' => array(
				'#type' => 'html',
				'#value' => '</div>'
			)
		)
	);
	
	return $form;
}

/**
 * milestone_edit_form()
 * 
 * This is the form that is rendered when editing or adding a milestone
 * 
 * @param mixed $mid
 * @param mixed $values
 * @return
 */
function milestone_edit_form($mid, $values = array())
{
	global $milestone_form, $op;
	
	if (!empty($values))
	{
		$milestone = new Milestone(
			array(
				'name' => $values['name'], 
				'date' => $values['date']
			)
		);
	}
	else if (!empty($mid))
	{
		$milestone = new Milestone($mid);
	}
	else
	{
		$milestone = new Milestone();
	}
	
	$inputs = array();	
	$form_id = render_unique_id('milestone-edit-' . $mid);
	
	$inputs['name'] = array(
		'#type' => 'textfield',
		'#id' => render_unique_id('edit-name'),
		'#title' => 'Name',
		'#value' => $milestone->name,
		'#size' => 60
	);
	$inputs['date'] = array(
		'#type' => 'textfield',
		'#id' => render_unique_id('edit-date'),
		'#title' => 'Date',
		'#value' => Milestone::formatted_date($milestone->date),
		'#size' => 60
	);
	$inputs['button_wrapper'] = array(
		'#type' => 'html',
		'#value' => '<div class="form-item-wrapper">'
	);
	$inputs['cancel'] = array(
		'#type' => 'submit',
		'#value' => 'Cancel',
		'#id' => render_unique_id('cancel'),
		'#attributes' => array(
			'class' => 'ui-button',
		)
	);
	
	if ($op == 'edit')
	{
		$inputs['cancel']['#attributes']['onclick'] = "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "milestone?op=edit&mid=" . $milestone->mid . "');";
		$inputs['delete'] = array(
			'#type' => 'submit',
			'#value' => 'Delete',
			'#id' => render_unique_id('delete'),
			'#attributes' => array(
				'class' => 'ui-button',
				'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "milestone?op=delete&subop=confirm&mid=" . $milestone->mid . "');"
			)
		);
		$inputs['save'] = array(
			'#type' => 'submit',
			'#value' => 'Save',
			'#id' => render_unique_id('save'),
			'#attributes' => array(
				'class' => 'ui-button',
				'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "milestone?op=edit&subop=save&mid=" . $milestone->mid . "');"
			)
		);
	}
	else if ($op == 'add')
	{
		$inputs['cancel']['#attributes']['onclick'] = "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "milestone');";
		$inputs['save'] = array(
			'#type' => 'submit',
			'#value' => 'Save',
			'#id' => render_unique_id('save'),
			'#attributes' => array(
				'class' => 'ui-button',
				'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "milestone?op=add&subop=save&mid=" . $milestone->mid . "');"
			)
		);
	}
	
	$inputs['button_wrapper_close'] = array(
		'#type' => 'html',
		'#value' => '</div>'
	);
		
	$milestone_form = array(
		'#id' => $form_id,
		'#action' => base_path() . 'milestone?op=edit&subop=save&mid=' . $milestone->mid,
		'#method' => 'POST',
		'#validator' => 'milestone_edit_validate',
		'#callback' => 'milestone_edit_submit',
		'#inputs' => $inputs, 
		'#name' => 'All fields are required.',
		'#attributes' => array(
			'class' => 'edit-milestone'
		)
	);
}

/**
 * milestone_search_submit()
 * 
 * @param mixed $form_result
 * @return
 */
function milestone_search_submit(&$form_result)
{
	global $milestone_table, $milestone_form;
	
	$values = $form_result['values'];
	
	$milestone_form = milestone_default_form();
	
	$milestone_form['#inputs']['name']['#value'] = (isset($values['name']) ? $values['name'] : '');
	
	$result = db_query("SELECT * FROM milestone WHERE mid > 0 AND name LIKE '%%%s%%' ORDER BY name", $values['name']);
	
	$headers = array('', 'Name', 'Date');
	$rows = array();
	while ($milestone = db_fetch_array($result))
	{
		$rows[] = array(
			'#cells' => array(
				'edit' => a(
					array(
						'#href' => base_path() . 'milestone?op=edit&mid=' . $milestone['mid'],
						'#anchor' => 'Edit',
						'#attributes' => array(
							'class' => 'action-link edit'
						)
					)
				),
				'name' => $milestone['name'],
				'date' => Milestone::formatted_date($milestone['date'])
			)
		);
	}
	
	if (empty($rows))
	{
		$rows[] = array(
			'#cells' => array(
				'no_results' => array(
					'#value' => '<h2 style="text-align:center;">Your search returned no results.</h2>',
					'#attributes' => array(
						'colspan' => count($headers)
					)
				)
			)
		);
	}
	
	$table_id = render_unique_id('milestone-table');
	$milestone_table = array(
		'#attributes' => array(
			'id' => $table_id,
			'border' => 1,
			'cellspacing' => 0,
			'cellpadding' => 8,
			'class' => 'selectable data-list-table'
		),
		'#header' => $headers,
		'#rows' => $rows
	);
}

/**
 * milestone_edit_validate()
 * 
 * @param mixed $form_result
 * @return
 */
function milestone_edit_validate(&$form_result)
{
	$values = $form_result['values'];
	if ($values['submit'] == 'Save' && isset($_GET['mid']))
	{
		$milestone = new Milestone();
		
		$reload = FALSE;
		if (!isset($values['name']))
		{
			$reload = TRUE;
			form_error('name', 'You must specify a name.');
		}
		else 
		{
			if (strlen($values['name']) >= 75)
			{
				$reload = TRUE;
				form_error('name', 'The name must be less than 75 characters.');
			}
			
			if ($values['name'] == $milestone->name)
			{
				$reload = TRUE;
				form_error('name', 'Please enter a name.');
			}
		}
		
		if (!isset($values['date']))
		{
			$reload = TRUE;
			form_error('date', 'You must specify date.');
		}
		else
		{
			$date = strtotime($values['date']);
			if ($date === FALSE)
			{
				$reload = TRUE;
				form_error('date', 'Please enter a valid date.');
				$form_result['values']['date'] = db_result(db_query('SELECT date FROM milestone WHERE mid=%d', $_GET['mid']));
			}
			
			if ($date !== FALSE && $date < time())
			{
				$reload = TRUE;
				form_error('date', 'Please enter a valid milestone date.');
				$form_result['values']['date'] = db_result(db_query('SELECT date FROM milestone WHERE mid=%d', $_GET['mid']));
			}
			else
			{
				$form_result['values']['date'] = $date;
			}
		}
		
		if ($reload)
		{
			milestone_edit_form($_GET['mid'], $form_result['values']);
		}
	}
	else if ($values['submit'] != 'Delete')
	{
		system_redirect(base_path() . 'milestone');
	}
}

/**
 * milestone_edit_submit()
 * 
 * @param mixed $form_result
 * @return
 */
function milestone_edit_submit(&$form_result)
{
	$values = $form_result['values'];
	if ($values['submit'] == 'Save')
	{
		global $op;
		
		$milestone = '';
		if ($op == 'edit')
		{
			$milestone = new Milestone($_GET['mid']);
		} 
		else if ($op = 'add')
		{
			$milestone = new Milestone();
		}
		
		$milestone->name = $values['name'];
		$milestone->date = $values['date'];
		
		$milestone->save();
		
		system_redirect(base_path() . 'milestone?op=edit&mid=' . $milestone->mid);
	}
	else if ($values['submit'] != 'Delete')
	{
		system_redirect(base_path() . 'milestone');
	}
}

/**
 * milestone_delete_confirmation_form()
 * 
 * @param mixed $mid
 * @return void
 */
function milestone_delete_confirmation_form($mid)
{
	global $milestone_form;
	
	$form_id = render_unique_id('milestone-delete');
	$milestone_form = array(
		'#id' => $form_id,
		'#action' => base_path() . 'milestone?op=delete&mid=' . $mid,
		'#method' => 'POST',
		'#validator' => 'milestone_delete_milestone_confirmation_validate',
		'#callback' => 'milestone_delete_milestone_confirmation_submit',
		'#inputs' => array(
			'confirm' => array(
				'#title' => 'Are you sure you want to delete this milestone?',
				'#type' => 'checkbox',
				'#description' => 'This milestone will be completely erased from the system.',
				'#value' => 1,
				'#checked' => FALSE
			),
			'submit' => array(
				'#type' => 'submit',
				'#value' => 'Delete',
				'#attributes' => array(
					'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "milestone?op=delete&mid=" . $mid . "');"
				)
			),
			'cancel' => array(
				'#type' => 'submit',
				'#value' => 'Cancel',
				'#attributes' => array(
					'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "milestone?op=delete&subop=cancel&mid=" . $mid . "');"
				)
			)
		)
	);
	
	if ($error = form_error('confirm'))
	{
		$milestone_form['#inputs']['confirm']['#attributes'] = array('class' => 'error');
		system_set_message($error, 'error');
	}
}

/**
 * milestone_delete_milestone_confirmation_validate()
 * 
 * @param mixed $form_result
 * @return void
 */
function milestone_delete_milestone_confirmation_validate(&$form_result)
{
	switch ($form_result['values']['submit']) 
	{
		case 'Delete':
			$confirmation_form = FALSE;
			if (!isset($form_result['values']['confirm']) || $form_result['values']['confirm'] != 1)
			{
				form_error('confirm', 'Please confirm that you would like to delete this milestone, or click Cancel.');
				$confirmation_form = TRUE;
			}
			
			if ($confirmation_form)
			{
				front_delete_developer_confirmation_form($form_result['values']);
			}
			
			break;
		case 'Cancel':
			
			break;
	}
}

/**
 * milestone_delete_milestone_confirmation_submit()
 * 
 * @param mixed $form_result
 * @return void
 */
function milestone_delete_milestone_confirmation_submit(&$form_result)
{
	if ($form_result['values']['submit'] == 'Delete')
	{
		if (isset($_GET['mid']))
		{
			$name = db_result(db_query('SELECT name FROM milestone WHERE mid=%d', $_GET['mid']));
			
			$name = db_query('DELETE FROM milestone WHERE mid=%d', $_GET['mid']);
			$relational_result = db_query('UPDATE task SET mid=0 WHERE mid=%d', $_GET['mid']);
			if ($name && $relational_result)
			{
				system_set_message('The following milestone was successfully deleted: <code>' . $name . '</code>');
				system_redirect(base_path() . 'milestone');
			}
		}
	}
	else
	{
		system_redirect(base_path() . 'milestone?op=edit&mid=' . $_GET['mid']);
	}
}
